package com.ocean.aws.aw;

import org.bukkit.entity.Player;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtIo;
import net.minecraft.nbt.NbtAccounter;
import net.minecraft.nbt.TagParser;
import net.minecraft.server.level.ServerPlayer;
import moe.plushie.armourers_workshop.core.capability.SkinWardrobe;
import moe.plushie.armourers_workshop.core.capability.SkinWardrobeStorage;
import moe.plushie.armourers_workshop.api.core.IDataSerializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public final class AWBridge {

    private ServerPlayer asNms(Player player) throws Exception {
        Object handle = player.getClass().getMethod("getHandle").invoke(player);
        return (ServerPlayer) handle;
    }

    public String exportWardrobeSnbt(Player player) throws Exception {
        ServerPlayer nms = asNms(player);
        CompoundTag tag = new CompoundTag();
        IDataSerializer enc = SkinWardrobeStorage.encoder(nms, tag);
        SkinWardrobe wardrobe = SkinWardrobe.of(nms);
        wardrobe.serialize(enc);
        return tag.toString();
    }

    public void importWardrobeFromSnbt(Player player, String snbt) throws Exception {
        ServerPlayer nms = asNms(player);
        CompoundTag tag = TagParser.parseTag(snbt);
        IDataSerializer dec = SkinWardrobeStorage.decoder(nms, tag);
        SkinWardrobe wardrobe = SkinWardrobe.of(nms);
        wardrobe.deserialize(dec);
        wardrobe.broadcast(nms);
    }

    public byte[] exportWardrobeCompressedBytes(Player player) throws Exception {
        ServerPlayer nms = asNms(player);
        CompoundTag tag = new CompoundTag();
        IDataSerializer enc = SkinWardrobeStorage.encoder(nms, tag);
        SkinWardrobe.of(nms).serialize(enc);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        NbtIo.writeCompressed(tag, baos);
        return baos.toByteArray();
    }

    public void importWardrobeCompressedBytes(Player player, byte[] compressed) throws Exception {
        ServerPlayer nms = asNms(player);
        CompoundTag tag = NbtIo.readCompressed(new ByteArrayInputStream(compressed), NbtAccounter.unlimitedHeap());
        IDataSerializer dec = SkinWardrobeStorage.decoder(nms, tag);
        SkinWardrobe wardrobe = SkinWardrobe.of(nms);
        wardrobe.deserialize(dec);
        wardrobe.broadcast(nms);
    }
}


